package cn.edu.scujcc;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ChannelService {
	@Autowired
	private ChannelRepository repo;
	
	public Channel createChannel(Channel c) {
		Channel result = null;
		result = repo.save(c);
		return result;
	}
	public Channel updateChannel(Channel c) {
		Channel result = null;
		result = getChannel(c.getId());
		if (result != null) {
			if (c.getName() != null) {
				result.setName(c.getName());
			}
			if (c.getDesc() != null) {
				result.setDesc(c.getDesc());
			}
			if (c.getUrl() != null) {
				result.setUrl(c.getUrl());
			}
			result = repo.save(result);
		}
		
		return result;
	}
	
	public List<Channel> getAllChannel() {
		List<Channel> result = null;
		result = repo.findAll();
		return result;
	}
	
	public Channel getChannel(String id) {
		Channel result = null;
		Optional<Channel> op = repo.findById(id);
		if (op.isPresent()) {
			result = op.get();
		}
		return result;
	}
	
	public boolean deleteChannel(String id) {
//		boolean result = false;
//		try {
//			repo.deleteById(id);
//			result = true;
//		} catch (Exception c) {
//			result = false;
//		}
		boolean result = true;
		try {
			repo.deleteById(id);
		} catch (Exception c) {
			result = false;
		}
		return result;
	}
	
	public List<Channel> searchChannel(String desc){
		List<Channel> result = null;
		result = repo.findByDesc(desc);
		return result;
	}
}
